/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import entity.IEntity;
import entity.Project;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

/**
 *
 * @author zergio
 */
public class ProjectDAO implements IDAO {

    @Override
    public void persist(IEntity entity, EntityManager em) {
        em.persist(entity);
    }

    @Override
    public IEntity find(Object id, EntityManager em) {
        return (Project) em.find(Project.class, (int) id);
    }

    @Override
    public void update(IEntity entity, EntityManager em) {
        em.merge(entity);
    }

    @Override
    public void delete(Object id, EntityManager em) {
        Project project = (Project) em.getReference(Project.class, (int) id);
        em.remove(project);
    }

    @Override
    public List<IEntity> getList(EntityManager em) {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(Project.class));
        Query q = em.createQuery(cq);
        return q.getResultList();
    }

    public List<Project> getProjectsByCalendar(Object id, EntityManager em) {
        List<Project> a = null;
        Query q = em.createQuery("SELECT u FROM Project u "
                + "WHERE u.calendar.id = :id").setParameter("id", (Integer) id);

        try {
            a = q.getResultList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return a;
    }
    
    public List<Project> getProjectsByName(String name, EntityManager em) {
        List<Project> a = null;
        Query q = em.createQuery("SELECT u FROM Project u "
                + "WHERE u.name = :name").setParameter("name", name);

        try {
            a = q.getResultList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return a;
    }
}
